package com.hsu.apibackend.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryV3Result;
import com.hsu.apibackend.mapper.PaymentInfoMapper;
import com.hsu.apibackend.model.entity.PaymentInfo;
import com.hsu.apibackend.model.vo.PaymentInfoVO;
import com.hsu.apibackend.service.PaymentInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * @Author Hsu琛君珩
 * @Date 2024-09-09
 * @Description 支付信息服务实现类，处理支付相关的数据保存操作
 * @Version v1.0.0
 */
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    /**
     * 创建支付信息记录
     *
     * @param paymentInfoVO 支付信息VO对象，包含支付相关的数据
     * @return boolean 返回保存结果，成功为true，失败为false
     */
    @Override
    public boolean createPaymentInfo(PaymentInfoVO paymentInfoVO) {
        String transactionId = paymentInfoVO.getTransactionId();
        String tradeType = paymentInfoVO.getTradeType();
        String tradeState = paymentInfoVO.getTradeState();
        String tradeStateDesc = paymentInfoVO.getTradeStateDesc();
        String successTime = paymentInfoVO.getSuccessTime();
        WxPayOrderQueryV3Result.Payer payer = paymentInfoVO.getPayer();
        WxPayOrderQueryV3Result.Amount amount = paymentInfoVO.getAmount();

        // 创建支付信息实体并设置相应属性
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderNo(paymentInfoVO.getOutTradeNo());
        paymentInfo.setTransactionId(transactionId);
        paymentInfo.setTradeType(tradeType);
        paymentInfo.setTradeState(tradeState);

        // 判断成功时间是否为空，若不为空则设置
        if (StringUtils.isNotBlank(successTime)) {
            paymentInfo.setSuccessTime(successTime);
        }
        paymentInfo.setOpenid(payer.getOpenid());
        paymentInfo.setPayerTotal(amount.getPayerTotal());
        paymentInfo.setCurrency(amount.getCurrency());
        paymentInfo.setPayerCurrency(amount.getPayerCurrency());
        paymentInfo.setTotal(amount.getTotal());
        paymentInfo.setTradeStateDesc(tradeStateDesc);

        // 将支付信息VO对象转为JSON字符串，保存至content字段
        paymentInfo.setContent(JSONUtil.toJsonStr(paymentInfoVO));

        // 保存支付信息实体
        return this.save(paymentInfo);
    }
}
